package com.acme.javaschool.intense.sems.sem2concurrency.pool.clients;

import com.acme.javaschool.intense.sems.sem2concurrency.pool.Pool;
import com.acme.javaschool.intense.sems.sem2concurrency.pool.data.PoolableObject;

import static java.lang.Thread.currentThread;
import static java.lang.Thread.sleep;

public class GetterClient<T> extends PoolClient<T> {

    public GetterClient(Pool<T> pool) {
        super(pool);
    }

    @Override
    public void run() {
        pool.getTestHelper().submitWork(1);
        PoolableObject<T> t = getPoolableObject();

        while (true) {
            if (pause()) break;
        }
    }

    protected boolean pause() {
        try {
            sleep(300);
        } catch (InterruptedException e) {
            return true;
        }
        return false;
    }

    protected PoolableObject<T> getPoolableObject() {
        PoolableObject<T> t = null;
        try {
//            t = pool.get();
//            t = pool.tryGet();
              t = pool.tryGet(100);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread() + ": exception: " + e.getMessage());
        }

        if (t == null) {
            pool.getTestHelper().recordFailure();
        } else {
            pool.getTestHelper().recordSuccess();
        }

        return t;
    }
}